<?php
/**
 * Paginator class
 * Calculates pagination variables for site.
 * @package PersonalHomePageFramework
 * @subpackage Paginator
 * @category Core
 * @author Rolands Atvars <rolands.atvars@gmail.com>
 * @copyright Copyright (c) 2009, Rolands Atvars
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License version 3 (GPLv3)
 */
class Paginator {
  /**
   * @var int how many items there are per page.
   * @access private
   */
  private $per_page = null;
  /**
   * @var int how many items there are in total in given result set
   * @access private
   */
  private $total = null;
  /**
   * @var int current pages number
   * @access private
   */
  private $current_page = null;
  /**
   * @var int next pages number
   * @access private
   */
  private $next_page = null;
  /**
   * @var mixed I honestly don't know what this is. Probably this is nothing.
   * @access private
   */
  private $model_where = null;
  
  /**
   * Initializes Paginator
   * @param array $options optional (per_page, total, current_page, model, model_opts)
   * @access public
   */
  public function __construct($options = array()) {
    if(!empty($options)) {
      foreach($options as $key => $value) {
        if($key == "per_page" or $key == "total" or $key == "current_page") {
          $this->$key = $value;
        }
        if($key == "model") {
          if(!isset($options["model_opts"])) {
            $options["model_opts"] = array();
          }
          $class = new $value();
          $this->total = $class->count($options["model_opts"]);
        }
      }
    }
  }
  
  /**
   * Gets next page number.
   * @return int|bool returns false if $current_page is invalid
   * @access public
   */
  public function get_next_page() {
    if($this->current_page == 1 or !is_numeric($this->current_page)) {
      return false;
    }
    else {
      return $this->current_page - 1;
    }
  }
  
  /**
   * Gets previous page number
   * @return int|bool returns false if $current_page is invalid
   * @access public
   */
  public function get_prev_page() {
    if(!is_numeric($this->current_page)) {
      return false;
    }
    
    if($this->total != null and $this->per_page != null) {
      $seen_items = $this->per_page * $this->current_page;
      if($seen_items >= $this->total) {
        return false;
      }
      else {
        return $this->current_page + 1;
      }
    }
    else {
      return $this->current_page + 1;
    }
  }
  
  /**
   * Calculates offset for LIMIT in SQL query.
   * @return int
   * @access public
   */
  public function get_offset() {
    $current_page = $this->current_page - 1;
    return $this->per_page * $current_page;
  }
  
  /**
   * Gets how many items are rendered per page.
   * @return int
   * @access public
   */
  public function get_per_page() {
    return $this->per_page;
  }
}
?>